<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/10/22
 * Time: 16:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\business;

use app\common\lib\Status;
use app\common\validate\Run as ValObj;
use app\common\model\mysql\Run as ModelObj;
use think\Exception;
use think\facade\Cache;

class Run extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * @return ModelObj|array|\think\Model|null
     * @throws Exception
     */
    public function getRunByDistanceById()
    {
        try {
            $result = $this->modelObj->where('status', Status::mysql_normal)
                ->find();
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        return $result;
    }

    public function add(array $data = [])
    {
        $this->isValidateAdd($data);
        try {
            $res = $this->getRunByDistanceById();
            if ($res) {
                $result = $res->save($data);
            } else {
                $result = $this->modelObj->insertAdd($data);
            }
        } catch (\Exception $e) {
            throw new Exception("查询错误");
        }
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}